<!DOCTYPE html>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
	<title>自定义promise</title>
	<style type="text/css">
	* {
		padding: 0;
		margin: 0;
	}
    </style>
</head>
<body>
	<div class="container">
		<h1>自定义promise</h1>
	</div>
	<script src="my-promise.js"></script>
	<script type="text/javascript">

	function task(resolve, reject, isAsync = false) {
		function innerTask() {
			console.log('开始执行' )
		
			var random = Math.random();
			var rand = Math.round(random)
			
			// resolve('success ' + random)
			reject('failed ' + random)


			resolve('success22 ' + random)
			reject('failed2333 ' + random)

			console.log('开始执行 complete' )
		}

		if(isAsync) {
			setTimeout(() => {
				innerTask()
			},1000)
		} else {
			innerTask()
		}
	}


	var p = new Promise((resolve, reject)=> {
		task(resolve, reject, 0)
	})

	console.log('then before', p)

	var pRet = p.then(value => {
		// throw '第一个then 抛出异常'
		console.info('value => ', value)
		// return new Promise((resolve, reject) => {
		// 	resolve('第一个then value  success')
		// 	reject('第一个then value  error')
		// })
		// 
		return 'sdfsdf'
	}, reason => {
		console.warn('reason => ', reason)
	})


	// 一个promise可以指定多个回调，多个回调都会执行
	p.then(value => {
		console.log('value2 => ', value)
		
	}, reason => {
		console.warn('reason2 => ', reason)
		return "第二个then reason " + reason
	})

	p.then(value => {
		console.log('value3 => ', value)
		return '第三个then value3 => ' + value
	}, reason => {
		console.warn('reason3 => ', reason)
	})

	console.log('then after', pRet)
	console.log('---------------------------------------------------------------\n')
	

	</script>
</body>
</html>